package com.ss.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @author Administrator
 * @description TODO
 * @date 2019/5/31 10:36
 **/
@Component
public class DataSourceConfigurer {
    /*//使用xml配置注入数据源
    @Autowired
    @Qualifier("datasource1")
    DruidDataSource datasource1;

    @Autowired
    @Qualifier("datasource2")
    DruidDataSource datasource2;*/

    @Autowired
    private Properties properties;

    @Bean(value="dynamicDataSource")
    public DynamicDataSource dynamicDataSource(){
        Map<Object,Object> targetDataSources = new HashMap<Object,Object>();
        String[] datasourceTypes = properties.get("datasourcePrefix").toString().split(",");
        for(String datasourceType : datasourceTypes){
            targetDataSources.put(datasourceType,getDataSource(datasourceType));
        }

        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        dynamicDataSource.setTargetDataSources(targetDataSources);
        dynamicDataSource.setDefaultTargetDataSource(targetDataSources.get(datasourceTypes[0]));
        return dynamicDataSource;
    }


    private DataSource getDataSource(String type){
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(properties.get(type+".driver").toString());
        druidDataSource.setUrl(properties.get(type+".url").toString());
        druidDataSource.setPassword(properties.get(type+".password").toString());
        druidDataSource.setUsername(properties.get(type+".username").toString());
        return druidDataSource;
    }

}
